﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Threading;

namespace SystemsAdmin
{
    public class OpenAuditRepository : ComputerRepository
    {
        public string DatabaseName {get; set;}
        public string DBAddress {get; set;}
        public string Username {get; set;}
        public string Password {get; set;}

        public List<Computer> GetAllComputers(string database_name,
            string db_address, string username, string password)
        {
            DatabaseName = database_name;
            DBAddress = db_address;
            Username = username;
            Password = password;
            return GetAllComputers();
        }

        /// <summary>
        /// Gets a list of all the computers stored in OpenAudit's database
        /// </summary>
        public List<Computer> GetAllComputers()
        {
            List<Computer> computers_in_db = new List<Computer>();
            MySqlConnection oMySqlConn = new MySqlConnection();
            oMySqlConn.ConnectionString = "Data Source=" + DBAddress +
                                          ";Database=" + DatabaseName +
                                          ";User ID=" + Username +
                                          ";Password=" + Password;
            string mySelectQuery = @"select distinct system_name, net_uuid, 
network_card.net_ip_address as ipaddress, net_mac_address from system
inner join network_card on net_uuid = system_uuid order by system_name";
            MySqlCommand myCommand = new MySqlCommand(mySelectQuery, oMySqlConn);
            oMySqlConn.Open();
            MySqlDataReader myReader;
            myReader = myCommand.ExecuteReader();
            // Always call Read before accessing data.
            while (myReader.Read())
            {
                Computer new_comp = new Computer(myReader.GetString("net_mac_address"),
                    myReader.GetString("system_name"),
                    myReader.GetString("ipaddress"));
                computers_in_db.Add(new_comp);
                new Thread(new_comp.Refresh).Start();
            }
            // always call Close when done reading.
            myReader.Close();
            // Close the connection when done with it.
            oMySqlConn.Close();
            return computers_in_db;

        }
    }
}
